<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="工单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="委托单位名称" prop="entrustedDepartmentName">
        <el-input
          v-model="queryParams.entrustedDepartmentName"
          placeholder="请输入委托单位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物种或样品名称" prop="speciesOrSampleName">
        <el-input
          v-model="queryParams.speciesOrSampleName"
          placeholder="请输入物种或样品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否需要CMA资质" prop="isNeedCma">
        <el-select v-model="queryParams.isNeedCma" placeholder="请选择是否需要CMA资质" clearable>
          <el-option
            v-for="dict in yes_or_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['entrust_order:entrust_order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['entrust_order:entrust_order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['entrust_order:entrust_order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="entrust_orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <!-- <el-table-column label="商务经理ID" align="center" prop="businessManagerId" width="70" />
      <el-table-column label="客户经理ID" align="center" prop="clientManagerId" width="70" /> -->
      <el-table-column label="项目名称" align="center" prop="clientName" width="70" />
      <el-table-column label="委托单位名称" align="center" prop="entrustedDepartmentName" />
      <el-table-column label="委托单位地址" align="center" prop="unitLocation" />
      <el-table-column label="开票发票抬头" align="center" prop="invoicingInvoiceHeader" />
      <el-table-column label="纳税人识别号" align="center" prop="taxpayerNumber" />
      <el-table-column label="物种或样品名称" align="center" prop="speciesOrSampleName" />
      <el-table-column label="最少的一个样本量" align="center" prop="minSampleCount" />
      <el-table-column label="样本类型" align="center" prop="sampleType">
        <template #default="scope">
          <dict-tag :options="sample_type" :value="scope.row.sampleType"/>
        </template>
      </el-table-column>
      <el-table-column label="委托要求完成时间" align="center" prop="entrustedFinishTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.entrustedFinishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否需要CMA资质" align="center" prop="isNeedCma">
        <template #default="scope">
          <dict-tag :options="yes_or_no" :value="scope.row.isNeedCma"/>
        </template>
      </el-table-column>
      <el-table-column label="客户电话" align="center" prop="clientPhone" />
      <el-table-column label="余样是否退还" align="center" prop="isNeedReturn">
        <template #default="scope">
          <dict-tag :options="yes_or_no" :value="scope.row.isNeedReturn"/>
        </template>
      </el-table-column>
      <el-table-column label="数量(平行样需累计)" align="center" prop="count" />
      <el-table-column label="选择时间" align="center" prop="time" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保存温度" align="center" prop="temperature" width="70" />
      <el-table-column label="订单时间" align="center" prop="orderTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['entrust_order:entrust_order:edit']"
            style="margin-left: 12px;"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['entrust_order:entrust_order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" v-model="open" width="1400px" append-to-body>
        <!--父-->
        <el-card class="box-card">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
                <el-col :span="23">
                    <el-row :gutter="15">
                        <el-col :span="12">
                            <el-form-item label="委托人名称" prop="clientName">
                                <el-input v-model="form.clientName" placeholder="请输入委托人名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户经理ID" prop="clientManagerId">
                                <el-input v-model="form.clientManagerId" disabled placeholder="系统自动填写" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="商务经理ID" prop="businessManagerId">
                                <el-input v-model="form.businessManagerId" disabled placeholder="系统自动填写" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="委托单位名称" prop="entrustedDepartmentName">
                                <el-input v-model="form.entrustedDepartmentName" placeholder="请输入委托单位名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="订单编号" prop="id">
                                <el-input v-model="form.orderId" disabled placeholder="系统自动填写" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="委托单位地址" prop="unitLocation">
                                <el-input v-model="form.unitLocation" placeholder="请输入委托单位地址" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开票发票抬头" prop="invoicingInvoiceHeader">
                                <el-input v-model="form.invoicingInvoiceHeader" placeholder="请输入开票发票抬头" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纳税人识别号" prop="taxpayerNumber">
                                <el-input v-model="form.taxpayerNumber" placeholder="请输入纳税人识别号" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物种或样品名称" prop="speciesOrSampleName">
                                <el-input v-model="form.speciesOrSampleName" placeholder="请输入物种或样品名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="最少的一个样本量" prop="minSampleCount">
                                <el-input v-model="form.minSampleCount" type="number" placeholder="请输入最少的一个样本量" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="样本类型" prop="sampleType">
                                <el-radio-group v-model="form.sampleType">
                                    <el-radio
                                        v-for="dict in sample_type"
                                        :key="dict.value"
                                        :label="parseInt(dict.value)"
                                    >{{dict.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="委托要求完成时间" prop="entrustedFinishTime">
                                <el-date-picker clearable
                                    v-model="form.entrustedFinishTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择委托要求完成时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否需要CMA资质" prop="isNeedCma">
                                <el-radio-group v-model="form.isNeedCma">
                                    <el-radio
                                        v-for="dict in yes_or_no"
                                        :key="dict.value"
                                        :label="parseInt(dict.value)"
                                    >{{dict.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户电话" prop="clientPhone">
                                <el-input v-model="form.clientPhone" placeholder="请输入客户电话" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="余样是否退还" prop="isNeedReturn">
                                <el-radio-group v-model="form.isNeedReturn">
                                    <el-radio
                                        v-for="dict in yes_or_no"
                                        :key="dict.value"
                                        :label="parseInt(dict.value)"
                                    >{{dict.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="数量(平行样需累计)" prop="count">
                                <el-input v-model="form.count" type="number" min="1" placeholder="请输入数量(平行样需累计)" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="选择时间" prop="time">
                                <el-date-picker 
                                    clearable
                                    v-model="form.time"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择选择时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="保存温度" prop="temperature">
                                <el-input v-model="form.temperature" placeholder="请输入保存温度" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="订单时间" prop="orderTime">
                                <el-date-picker clearable
                                    v-model="form.orderTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择订单时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
            </el-form>
        </el-card>
        <!--子-->
        <el-card class="box-card">
          <h3 style="padding: 10px 30px; font-weight: 550; font-size: 22px;">检测项目</h3>

          <el-table ref="childTable" v-loading="child.loading" :data="child.warehousingList" @selection-change="handleChildSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="入库ID" align="center" prop="id" />
              <el-table-column label="项目名称" align="center" prop="projectName" />
              <el-table-column label="项目编号" align="center" prop="projectCode" />
              <el-table-column label="接样日期" align="center" prop="warehousingDate" width="180">
                  <template #default="scope">
                  <span>{{ parseTime(scope.row.warehousingDate, '{y}-{m}-{d}') }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="收样编号" align="center" prop="warehousingCode" />
              <el-table-column label="送样人ID" align="center" prop="senderId" />
              <el-table-column label="送样人名称" align="center" prop="senderName" />
              <el-table-column label="备注" align="center" prop="remark" />
          </el-table>
          <pagination
              v-show="child.total>0"
              :total="child.total"
              v-model:page="child.queryParams.pageNum"
              v-model:limit="child.queryParams.pageSize"
              @pagination="getChildList"
          />
        </el-card >

        <el-card class="box-card">
          <h3 style="padding: 10px 30px; font-weight: 550; font-size: 22px;">流程</h3>

          <el-table ref="flowProcessTable" v-loading="flowProcessChild.loading" :data="flowProcessChild.flowProcessList" :current-row-key="flowProcessChild.selectedId" @current-change="handleFlowProcessCurrentChange">
              <el-table-column label="选择" width="55" align="center">
                <template #default="scope">
                  <el-radio 
                    v-model="flowProcessChild.selectedId" 
                    :label="scope.row.id"
                    @change="handleFlowRadioChange(scope.row)"
                    class="radio-hide-text"
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column label="流程ID" align="center" prop="id" />
              <el-table-column label="流程名称" align="center" prop="processName" />
              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
          </el-table>
          <pagination
            v-show="flowProcessChild.total > 0"
            :total="flowProcessChild.total"
            v-model:page="flowProcessChild.queryParams.pageNum"
            v-model:limit="flowProcessChild.queryParams.pageSize"
            @pagination="getFlowProcessList"
          />
        </el-card >
        <!--底部按钮-->
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { listEntrust_order, getEntrust_order, delEntrust_order, updateEntrust_order } from "@/api/entrust_order/entrust_order"
import { listProcess } from "@/api/flow/process.js"
import { listWarehousing } from "@/api/custom/warehousing"

const { proxy } = getCurrentInstance();
const { sample_type, yes_or_no } = proxy.useDict("sample_type", "yes_or_no");

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 工单表格数据
const entrust_orderList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)

const data = reactive({
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    clientName: null,
    entrustedDepartmentName: null,
    speciesOrSampleName: null,
    isNeedCma: null,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    clientPhone: [
      { pattern: /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    clientName: [
      { required: true, message: "委托人名称不能为空", trigger: "blur" }
    ],
    speciesOrSampleName: [
      { required: true, message: "物种或样品名称不能为空", trigger: "blur" }
    ],
    minSampleCount: [
      { required: true, message: "最少的一个样本量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data);

// ======================
const child = ref({
  // 入库列表加载中
  loading: true,
  // 总条数
  total: 0,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: undefined
  },
  // 入库列表
  warehousingList: [],
  // 选中的入库列表
  ids: []
})

const flowProcessChild = ref({
  loading: true,
  total: 0,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  flowProcessList: [], //存储流程列表
  selectedId: null,
})

/** 查询工单列表 */
function getList() {
  loading.value = true
  listEntrust_order(queryParams.value).then(response => {
    entrust_orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 表单重置
function reset() {
  form.value = {
    orderId: null,
    businessManagerId: null,
    clientManagerId: null,
    clientName: null,
    entrustedDepartmentName: null,
    unitLocation: null,
    invoicingInvoiceHeader: null,
    taxpayerNumber: null,
    speciesOrSampleName: null,
    minSampleCount: null,
    sampleType: null,
    entrustedFinishTime: null,
    isNeedCma: null,
    clientPhone: null,
    isNeedReturn: null,
    count: null,
    time: null,
    temperature: null,
    orderTime: null,  
  }
  proxy.resetForm("formRef")
  child.value.warehousingList = []
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm")
  handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length!==1
  multiple.value = !selection.length
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const orderId = row.orderId || ids.value
  // 子入库ID列表
  getEntrust_order(orderId).then(response => {
    form.value = response.data.entrustOrder
    
    getFlowProcessList().then(() => {
      flowProcessChild.value.selectedId = response.data.flowProcessId;//选过流程回显
      form.value.flowProcessId = response.data.flowProcessId;
      
      open.value = true
      title.value = "修改工单"

      // 点击修改查询子列表
      getChildList().then(() => {
        // 给ids赋值
        child.value.ids = response.data.warehousingIds
        // 将选中的入库单勾选
        child.value.warehousingList.forEach(row => {
          if (response.data.warehousingIds.includes(row.id)) {
            proxy.$refs.childTable.toggleRowSelection(row, true)
          }
        })
      });
    });
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (!valid) return
    updateEntrust_order({
      entrustOrder: form.value,
      warehousingIds: child.value.ids,
    }).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      open.value = false
      getList()
    })
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除工单编号为"' + orderIds + '"的数据项？').then(function() {
    return delEntrust_order(orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('entrust_order/entrust_order/export', {
    ...queryParams.value
  }, `entrust_order_${new Date().getTime()}.xlsx`)
}

// ===============================
/** 查询工单样品接收入库登记列表 */
function getChildList() {
  return new Promise((resolve, reject) => {
    child.value.loading = true
    listWarehousing(child.value.queryParams).then(response => {
      child.value.warehousingList = response.rows
      // 需要把orderId
      child.value.total = response.total
      child.value.loading = false
      resolve()
    }).catch(e => {
      reject()
    })
  })
}
// 多选框选中数据
function handleChildSelectionChange(selection) {
  child.value.ids = selection.map(item => item.id)
}

/** 查询流程列表 */
function getFlowProcessList() {
  return new Promise((resolve, reject) => {
    flowProcessChild.value.loading = true,
    listProcess(flowProcessChild.value.queryParams).then((response) => {
      console.log('获取的流程列表：',response);
      flowProcessChild.value.flowProcessList = response.rows;
      flowProcessChild.value.total = response.total;
      flowProcessChild.value.loading = false;

      resolve();
    }).catch((e) => {
      flowProcessChild.value.loading = false;
      reject(e);
    })
  })
}

/** 查询流程列表单选事件 */
function handleFlowRadioChange(row) {
  flowProcessChild.value.selectedId = row.id;
  form.value.flowProcessId = row.id;
  // 设置当前行高亮
  proxy.$refs.flowProcessTable.setCurrentRow(row);
}
getList()
</script>

<style scoped>
.box-card {
  margin: 0 20px 20px 20px;
}
/* 隐藏单选按钮的文本 */
:deep(.el-radio__label) {
  display: none;
}
/* 选中行样式 */
:deep(.current-row) {
  background-color: #f5f7fa !important;
}
</style>